﻿using System;
using System.Linq;
using System.Security.Claims;
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;

namespace K9Nano.Admin.Weixin.OAuth
{
    public sealed class WeixinOAuthOptions : OAuthOptions
    {
        public WeixinOAuthOptions()
        {
            CallbackPath = new PathString("/signin-weixin");
            AuthorizationEndpoint = WeixinDefaults.AuthorizationEndpoint;
            QrCodeAuthorizationEndpoint = WeixinDefaults.QrCodeAuthorizationEndpoint;
            TokenEndpoint = WeixinDefaults.TokenEndpoint;
            UserInformationEndpoint = WeixinDefaults.UserInformationEndpoint;
            SaveTokens = false;

            //Scope 表示应用授权作用域。
            //网页上登录（非微信浏览器）需要两个Scope，一个是UserInfo，一个是Login
            Scope.Add("snsapi_userinfo");
            Scope.Add("snsapi_login");

            IsWeChatBrowser = (r) => r.Headers[HeaderNames.UserAgent].ToString().Contains("MicroMessenger", StringComparison.OrdinalIgnoreCase);
            
            ClaimActions.MapJsonKey(JwtClaimTypes.Subject, "openid");
            ClaimActions.MapJsonKey(JwtClaimTypes.NickName, "nickname");
            ClaimActions.MapJsonKey(JwtClaimTypes.Gender, "sex", ClaimValueTypes.Integer);
            ClaimActions.MapJsonKey("urn:wechat:province", "province");
            ClaimActions.MapJsonKey("urn:wechat:city", "city");
            ClaimActions.MapJsonKey(JwtClaimTypes.Profile, "headimgurl");
            ClaimActions.MapCustomJson("urn:wechat:privilege", user =>
            {
                 if (user.TryGetProperty("privilege", out var privilege))
                 {
                     return string.Join(",", privilege.EnumerateArray().Select(x => x.GetString()));
                 }

                 return string.Empty;
             });
            ClaimActions.MapJsonKey("urn:wechat:unionid", "unionid");
        }

        public string QrCodeAuthorizationEndpoint { get; set; }

        /// <summary>
        /// IdentityServer4 的登录URL
        /// </summary>
        public string LoginUrl { get; set; } = "Weixin/Login";
        
        /// <summary>
        /// IdentityServer4认证中心地址
        /// </summary>
        public string Authority { get; set; }

        /// <summary>
        /// 是否是微信内置浏览器
        /// </summary>
        public Func<HttpRequest, bool> IsWeChatBrowser { get; set; }

        public override void Validate()
        {
            // do nothing
        }
    }
}